﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Business.Fin;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Sales;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Pur;

namespace ESOL.WinUI.Finance
{
    public partial class frmMaintainAPInvoice : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public FinBillingEntity SelectedBilling { get; set; }
        private List<InvImportItemEntity> mListImportItem;
        #endregion

        #region Constructor
        public frmMaintainAPInvoice()
        {
            InitializeComponent();
            if (SelectedBilling == null)
            {
                SelectedBilling = new FinBillingEntity();
                SelectedBilling.BillingId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainAPInvoice(List<InvImportItemEntity> list, MstSupplierEntity supplier)
        {
            InitializeComponent();
            if (SelectedBilling == null)
            {
                SelectedBilling = new FinBillingEntity();
                SelectedBilling.BillingId = Guid.NewGuid().ToString();
            }

            mListImportItem = list;
            txtSupplier.Tag = supplier;
        }
        #endregion

        #region Functions
        private void SetFieldsBySupplier(MstSupplierEntity supplier)
        {
            if (supplier != null)
            {
                txtSupplier.Tag = supplier;
                txtSupplier.Text = supplier.SupplierName;
                UICommonFunctions.BindContactCombobox(cmbSupplierContact, supplier.SupplierId, false);
                if (cmbSupplierContact.Items.Count > 0)
                {
                    cmbSupplierContact.SelectedIndex = 0;
                    MstSupplierContactEntity entity = (MstSupplierContactEntity)cmbSupplierContact.SelectedItem;
                    if (entity != null)
                    {
                        txtSupplierContactPhone.Text = entity.ContactMobilephone;
                    }
                }
                FinSupplierAccountEntity account = FinSupplierAccountBs.GetBySupplierId(supplier.SupplierId);
                if (account != null)
                {
                    txtNeedPayAmount.Text = account.PayableAmount.ToString("#0.00");
                }
                else
                {
                    txtNeedPayAmount.Text = "0.00";
                }
            }
            else
            {
                txtSupplier.Tag = null;
                txtSupplier.Text = "";
                UICommonFunctions.BindContactCombobox(cmbSupplierContact, "", false);
                txtSupplierContactPhone.Text = "";
                txtNeedPayAmount.Text = "0.00";
            }
        }
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPayType, "PAT", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItemWithCode(cmbOrderType, "CFT", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbBillingType, "BILLTYPE", false);
        }
        private void SetFields()
        {
            if (SelectedBilling == null)
            {
                return;
            }
            txtBillingCode.Text = SelectedBilling.BillingCode;
            if (string.IsNullOrEmpty(txtBillingCode.Text))
            {
                txtBillingCode.Text = "自动生成";
            }
            if (string.IsNullOrEmpty(SelectedBilling.SupplierId) == false)
            {
                MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(SelectedBilling.SupplierId);
                SetFieldsBySupplier(supplier);
            }
            if (SelectedBilling.BillingDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
                SelectedBilling.BillingDate.ToString("yyyy-MM-dd") == "0001-01-01")
            {
                dtpBillingDate.EditValue = null;
            }
            else
            {
                dtpBillingDate.EditValue = SelectedBilling.BillingDate;
            }
            if (ThisActionType == ActionType.New)
            {
                if (CommonParameter.CurrentUser.PersonEntity != null)
                {
                    txtBillingPerson.Tag = CommonParameter.CurrentUser.PersonEntity;
                    txtBillingPerson.Text = CommonParameter.CurrentUser.PersonEntity.NameCn + " (" + CommonParameter.CurrentUser.PersonEntity.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedBilling.BillingPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedBilling.BillingPerson);
                    if (person != null)
                    {
                        txtBillingPerson.Tag = person;
                        txtBillingPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            txtBillingAmount.Text = SelectedBilling.BillingAmount.ToString("#0.00");
            cmbStatus.SetSelectedValue(SelectedBilling.Status);
            cmbCurrency.SetSelectedValue(SelectedBilling.Currency);
            cmbPayType.SetSelectedValue(SelectedBilling.PayType);
            cmbOrderType.SetSelectedValue(SelectedBilling.OrderType);
            cmbBillingType.SetSelectedValue(SelectedBilling.BillingType);
            txtInvoiceNo.Text = SelectedBilling.InvoiceNo;
            txtRemark.Text = SelectedBilling.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedBilling.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedBilling.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedBilling.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedBilling.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedBilling.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedBilling.ApprovedBy);
        }
        private void SetEntity()
        {
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SelectedBilling.SupplierId = ((MstSupplierEntity)txtSupplier.Tag).SupplierId;
            }
            if (dtpBillingDate.EditValue != null)
            {
                SelectedBilling.BillingDate = Convert.ToDateTime(dtpBillingDate.EditValue.ToString());
            }
            if (txtBillingPerson.Tag != null && txtBillingPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedBilling.BillingPerson = ((MstPersonEntity)txtBillingPerson.Tag).PersonId;
            }
            SelectedBilling.BillingAmount = CommonFunctions.ToDecimal(txtBillingAmount.Text);
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedBilling.Currency = cmbCurrency.SelectedValue.ToString();
            }
            if (cmbPayType.SelectedValue != null && cmbPayType.SelectedValue.ToString().Trim() != "")
            {
                SelectedBilling.PayType = cmbPayType.SelectedValue.ToString();
            }
            if (cmbOrderType.SelectedValue != null && cmbOrderType.SelectedValue.ToString().Trim() != "")
            {
                SelectedBilling.OrderType = cmbOrderType.SelectedValue.ToString();
            }
            if (cmbBillingType.SelectedValue != null && cmbBillingType.SelectedValue.ToString().Trim() != "")
            {
                SelectedBilling.BillingType = cmbBillingType.SelectedValue.ToString();
            }
            SelectedBilling.InvoiceNo = txtInvoiceNo.Text;

            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedBilling.Status = "STATUS02";
            }

            SelectedBilling.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedBilling.CreatedDate = DateTime.Now;
                SelectedBilling.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedBilling.LastModifiedDate = DateTime.Now;
                SelectedBilling.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtSupplier.Text))
            {
                MessageBox.Show("供应商不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtBillingPerson.Text))
            {
                MessageBox.Show("经手人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbCurrency.Text))
            {
                MessageBox.Show("货币类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbPayType.Text))
            {
                MessageBox.Show("款项类别不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            //if (string.IsNullOrEmpty(cmbOrderType.Text))
            //{
            //    MessageBox.Show("核算项目不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return false;
            //}
            if (string.IsNullOrEmpty(cmbBillingType.Text))
            {
                MessageBox.Show("发票类别不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpBillingDate.EditValue == null)
            {
                MessageBox.Show("发票日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtBillingAmount.Text))
            {
                MessageBox.Show("发票金额不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtInvoiceNo.Text))
            {
                MessageBox.Show("发票号码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (CommonFunctions.ToDecimal(txtDiffAmount.Text) != 0)
            {
                DialogResult dr = MessageBox.Show("发票金额与清单金额有差额，是否继续？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }
            }
            return true;
        }
        private List<FinMapBillingImportEntity> GetListMap()
        {
            List<FinMapBillingImportEntity> list = new List<FinMapBillingImportEntity>();
            if (gvMain.DataSource == null)
            {
                return list;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (DataRow dr in dt.Rows)
            {
                FinMapBillingImportEntity entity = new FinMapBillingImportEntity(dr);
                list.Add(entity);
            }
            return list;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    bool isSuccessful = FinBillingBs.SaveBilling(true, SelectedBilling, GetListMap());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    bool isSuccessful = FinBillingBs.SaveBilling(false, SelectedBilling, GetListMap());
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    SelectedBilling.ApprovedDate = DateTime.Now;
                    SelectedBilling.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = FinBillingBs.ApproveBilling(SelectedBilling);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        private void BindDataGrid()
        {
            DataTable dt = FinMapIoBpaBs.GetImportByBillingId(SelectedBilling.BillingId);
            gvMain.DataSource = dt;
            mListImportItem = new List<InvImportItemEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                InvImportItemEntity entity = new InvImportItemEntity(dr);
                mListImportItem.Add(entity);
            }
            ResetItemAmount();
        }
        private DataTable GetNewDataTable(DataTable table)
        {
            DataTable dt = FinMapIoBpaBs.GetImportByBillingId("");
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    DataRow row = dt.NewRow();
                    foreach (DataColumn column in table.Columns)
                    {
                        if (dt.Columns.Contains(column.ColumnName))
                        {
                            row[column.ColumnName] = table.Rows[i][column.ColumnName];
                        }
                    }
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }
        private void ResetItemAmount()
        {
            decimal itemAmount = 0;
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt == null)
            {
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                itemAmount += CommonFunctions.ToDecimal(dr["BILLING_AMOUNT"].ToString());
            }
            txtItemAmount.Text = itemAmount.ToString("#0.00");
            decimal diffAmount = CommonFunctions.ToDecimal(txtBillingAmount.Text) - itemAmount;
            txtDiffAmount.Text = diffAmount.ToString("#0.00");
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SetFieldsBySupplier((MstSupplierEntity)txtSupplier.Tag);
            }
            if (ThisActionType != ActionType.New && SelectedBilling != null)
            {
                BindDataGrid();
            }
        }
        DataRow drSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedBilling = new FinBillingEntity();
                SelectedBilling.BillingId = Guid.NewGuid().ToString();
                SetFields();
            }
        }
        protected override void Click_Approve()
        {
            if (SelectedBilling == null)
            {
                return;
            }
            SelectedBilling.Status = "STATUS03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (SelectedBilling == null)
            {
                return;
            }
            SelectedBilling.Status = "STATUS04";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                SetFieldsBySupplier(frm.SelectedSupplier);
            }
            else
            {
                SetFieldsBySupplier(null);
            }
        }

        private void txtBillingPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtBillingPerson.Text = frm.SelectedPerson.NameCn;
                txtBillingPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtBillingPerson.Text = "";
                txtBillingPerson.Tag = null;
            }
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {

        }

        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.Approve || ThisActionType == ActionType.View)
            {
                return;
            }
            Inv.frmMaintainImportItemsQuery frm = new Inv.frmMaintainImportItemsQuery(true);
            frm.BillingStatus = "未开票";
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDataTable != null)
            {
                mListImportItem = new List<InvImportItemEntity>();
                DataTable dt = GetNewDataTable(frm.SelectedDataTable);
                gvMain.DataSource = dt;
                foreach (DataRow dr in dt.Rows)
                {
                    InvImportItemEntity entity = new InvImportItemEntity(dr);
                    mListImportItem.Add(entity);
                }
            }
            else
            {
                mListImportItem = null;
                gvMain.DataSource = null;
            }
            ResetItemAmount();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("BILLING_AMOUNT"))
            {
                ResetItemAmount();
            }
        }

        private void btnShowDetail_Click(object sender, EventArgs e)
        {
            if (txtSupplier.Tag == null || txtSupplier.Tag.GetType() != typeof(MstSupplierEntity))
            {
                MessageBox.Show("请先选择收款方！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            MstSupplierEntity supplier = (MstSupplierEntity)txtSupplier.Tag;
            frmMaintainBillingHistory frm = new frmMaintainBillingHistory(supplier);
            frm.ShowDialog();
        }

        private void txtBillingAmount_EditValueChanged(object sender, EventArgs e)
        {
            ResetItemAmount();
        }

        #endregion
    }
}
